/**
 * Created by cchen on 2015/4/16.
 */
var Users = mongoose.model('user');
var shareAppName = mongoose.model('mobile_app_shareAppName_restful');
var Share = mongoose.model('mobile_app_user_share_restful');
var NeighbourActivity = mongoose.model('activity_neighbour');
var Question = mongoose.model('question');
var SpecialTopics = mongoose.model('system_specialTopics');
var mysqlUtil = require('../../common/utils/mysqlUtil');
var toolUtil = require('../../common/utils/toolUtil');
var moment = require('moment');
var async = require('async');
var replyAt = mongoose.model('question_replyAt');
var SystemMessage = mongoose.model('system_messages');
var invitationShare = mongoose.model('user_invitation_share');
var Goods = mongoose.model('goods');
var communityActivity = mongoose.model('activity_community');
var shareContent = mongoose.model('mobile_app_share_content');
var topic = mongoose.model('topic');
/*  宝宝树66小区二次改造    add   chenf  20170714   start   */
var taskService = require('./../taskService');
/*  宝宝树66小区二次改造    add   chenf  20170714   end   */

exports.shareIsExisted = function (params, callback) {
    Share.findOne(params, callback);
};

exports.addNewShare = function (userId, feedsId, targetApp, feedsType) {
    var newShare = new Share();
    newShare.userId = userId;
    newShare.feedsId = feedsId;
    newShare.shareTo = targetApp;
    newShare.feedsType = feedsType;
    newShare.numberOfClick = 0;
    newShare.save();
    return newShare
};

var typeURL = {
    question: '/pages/static/mobile/partials/share/web/index.html',
    activity: '/pages/static/mobile/partials/share/web/index.html',
    specialTopic: '/pages/static/mobile/partials/share/web/index.html',
    app: "/pages/static/mobile/partials/share/app/index.html",
    app_wx: app_wx
};
var logoURl = "/img/shareLogo.png";

exports.urlGenerate = function (shareObj) {
    /*  宝宝树66小区二次改造    mod   dayu  20170727   start   */
    //return needHttp(backOfficeHost) + typeURL[shareObj.feedsType] + "?shareId=" + shareObj._id;
    return needHttp(questionShareHost) + typeURL[shareObj.feedsType] + "?shareId=" + shareObj._id;
    /*  宝宝树66小区二次改造    mod   dayu  20170727   end   */
};

exports.getShareById = function (shareId, callback) {
    Share.findOne({"_id": shareId}, callback);
};

exports.getNeighbourActivity = function (activityId, callback) {
    NeighbourActivity.findOne({_id: activityId}, 'title desc category images replies partake browserCount community dateCreated createdBy activityType deadline', callback).populate("community", "communityName").populate('replies.repliedBy', 'nickName images').populate('partake.user', 'nickName images').populate('createdBy', 'nickName images')
};

exports.getQuestion = function (questionId, callback) {
    Question.findOne({_id: questionId}, 'desc category images replies browserCount community dateCreated createdBy', callback).populate("community", "communityName").populate('replies.repliedBy', 'nickName images').populate('createdBy', 'nickName images')
};

exports.getSpecialTopic = function (topicId, callback) {
    SpecialTopics.findOne({_id: topicId}, callback);
};

exports.updateShareCount = function (shareObj, callback) {
    if (shareObj._id == '1') {
        Share.update({uuid: shareObj.uuid, userId: shareObj.userId}, {
            $inc: {numberOfClick: 1},
            dateLastModified: new Date(),
            feedsType: shareObj.feedsType,
            feedsId: shareObj.feedsId
        }, {upsert: true}, callback)
    } else {
        Share.update({_id: shareObj._id}, {$inc: {numberOfClick: 1}}, callback);
    }
};

//exports.getAppInvitation=function(userId,platform,sysInfo,targetApp,callback){
//    Users.findOne({_id:userId},callback)
//}

exports.shareApp = function (userId, targetApp, callback) {
    var feedsType = 'app';
    exports.shareIsExisted({userId: userId, feedsType: feedsType, shareTo: targetApp}, function (err, obj) {
        if (err) {
            callback(err, null)
        }
        if (!obj) {
            //obj = exports.addNewShare(userId, null, targetApp, feedsType)
        }
        exports.getUser(userId, function (err, userObj) {
            if (err) {
                callback(err, null)
            }
            var nowDate = new Date().getTime();
            var community = userObj.community._id + '';
            var sql = 'select voucher_name,voucher_val from voucher_reward_rule r,voucher_type t where r.from_time<? and r.to_time>? and r.reward_source=2 and r.community_id=? and t.id=r.voucher_type_id';

            //mysqlUtil.query(sql, [nowDate, nowDate, community], function (err, result) {
            var prize = '奖励';
            var value = 0;
            prize = INVITE_SCORE + '奖励';
            value = INVITE_SCORE;

            var data = {
                //title:  userObj.nickName + '给你打了个招呼',
                title: '来，跟我一起逛66',
                desc: "在宝宝树66小区，快速认识新邻居，跟周边邻居、好友一起带娃，互相置换闲置，还能分享小区周边的活动信息哦",
                /*  宝宝树66小区二次改造    mod   dayu  20170727   start   */
                //image: needHttp(backOfficeHost) + logoURl,
                image: needHttp(questionShareHost) + logoURl,
                /*  宝宝树66小区二次改造    mod   dayu  20170727   end   */
                //"url":exports.urlGenerate(obj)+"&fromUserId="+userObj._id+"&inviteCode="+userObj.invitationCode,
                "url": appShareUrl + "?userObjId=" + userObj._id + "&inviteCode=" + userObj.invitationCode,
                "invitationCode": userObj.invitationCode,
                prize: prize,
                value: value
            };
            callback(null, {obj: data});
            //});
        })
    })
};

var needHttp = function (url) {
    if (url.indexOf("http://") === -1) {
        return "http://" + url;
    }
    return url
};

var imageRefactor = function (url) {
    var array = url.replace("http://", "").split("/");
    var defaultURL = backOfficeHost + logoURl;
    if (array.length <= 1) {
        return defaultURL
    }
    var urlArray = url.split("/");
    var fileArray = urlArray[urlArray.length - 1].split(".");

    if (fileArray.length === 2) {
        fileArray[0] = fileArray[0] + "_120-120";
        var fileStr = fileArray.join(".");
        urlArray[urlArray.length - 1] = fileStr;
        return urlArray.join("/");
    } else {
        return defaultURL
    }
};

var getImageURL = function (images) {
    var imageURL = '';
    if (images && images.length > 0) {
        if (images[0].imageURL.indexOf('http://') === -1) {
            imageURL = fastDfsHostIp + images[0].imageURL
        } else {
            imageURL = images[0].imageURL;
        }
        //if (images[0].imageURL.indexOf('http://res.66xiaoqu.com') != -1) {
        //    imageURL = imageRefactor(imageURL);
        //}
    }
    else {
        imageURL = backOfficeHost + logoURl
    }
    return needHttp(imageURL)
};

var getShareImageURL = function (images) {
    var imageURL = '';
    if (images && images.length > 0 && images[0].imageURL != null) {
        logger.info(images[0]);
        if (images[0].imageURL.indexOf('http://') === -1) {
            imageURL = imgHost + images[0].imageURL + "?imageView2/1/w/100/h/100/q/75";
        } else {
            imageURL = images[0].imageURL;
        }
        //if (images[0].imageURL.indexOf('http://res.66xiaoqu.com') != -1) {
        //    imageURL = imageRefactor(imageURL);
        //}
    }
    else {
        imageURL = backOfficeHost + logoURl
    }
    return needHttp(imageURL)
};

var shareData = function (title, desc, images, shareObj, timestamp, userId, topicObj) {

    var url = topicObj.url;
    if (url.indexOf('?') != -1) {
        url += '&topic=share'
    } else {
        url += '?topic=share'
    }
    desc = desc ? (desc.length > 200 ? desc.substring(0, 200) : desc) : " ";
    var image = getShareImageURL(images);
    if (topicObj != null && topicObj.flag == 'video') {
        url = h5Host + '/app/video/outsite.html?v=1';
        title = '终于等到你，记录我们相爱一周年的微电影';
        desc = '66爱好邻居，我们的一周年大片';
        image = 'http://' + backOfficeHost + '/img/share_icon.jpg'
    }

    return {
        title: title,
        desc: desc,
        image: image,
        "url": url
    }
};

exports.shareDataService = function (title, desc, images, category) {
    var str = desc ? (desc.length > 200 ? desc.substring(0, 200) : desc) : " ";
    str = str.replace(/[\uD800-\uDBFF]$/, '');

    return {
        title: title,
        desc: str,
        image: getShareImageURL(images),
        /*  宝宝树66小区二次改造    mod   dayu  20170727   start   */
        //url: needHttp(backOfficeHost) + typeURL[category] + '?v=1.0'
        url: needHttp(questionShareHost) + typeURL[category] + '?v=1.0'
        /*  宝宝树66小区二次改造    mod   dayu  20170727   end   */
    }
};

/*  宝宝树66小区二次改造    add   luolh  20170726   start   */
exports.shareBeforeService = function (url, callback) {
    url = encodeURIComponent(url);
    var apiUrl = "http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long="+url;
    restClient.get(apiUrl, function (data, response) {
            if (response.statusCode == 200) {
                logger.info(data);
                var jsonResult = data; //JSON.parse(data);
                callback(null, {shortUrl : jsonResult[0].url_short, longUrl : jsonResult[0].url_long});
            } else {
                // logger.error(response);
                callback({message:"分享,网络错误!"}, null);
            }
        });
}
/*  宝宝树66小区二次改造    add   luolh  20170726   end   */

exports.shareCallbackService = function (input, callback) {
    if (input.feedsId != null) {
        if (input.feedsId.indexOf('share_detail.html') != -1) {
            input.feedsType = 'goods';
        } else if (input.feedsId.indexOf('coco.html') != -1) {
            input.feedsType = 'coco';
        } else if (input.feedsId.indexOf('christmas.html') != -1) {
            input.feedsType = 'christmas';
        }
        /*  宝宝树66小区二次改造    add   chenf  20170724   start   */
        taskService.finishTaskService(input.userId, 'share', function(err,result){
            callback(err, null);
        });
        /*  宝宝树66小区二次改造    add   chenf  20170724   end   */
    }

    var temp = new Share(input);
    temp.save(function (err, result) {
        Users.findOne({_id: input.userId}, 'dateCreated', function (err, user) {
            if (user != null) {
                var time = new Date().getTime() - user.dateCreated.getTime();

                if ((input.feedsId && input.feedsId.indexOf('outsite.html') != -1) || input.feedsType == null) {
                    callback(null, time < 604800000)
                } else {
                    callback(null, false)
                }
            } else {
                callback(null, false);
            }
        })
    });
};

exports.shareSpectialTopic = function (userId, targetApp, topicId, callback) {
    var feedsType = 'specialTopic';
    exports.shareIsExisted({
        userId: userId,
        feedsType: feedsType,
        feedsId: topicId,
        shareTo: targetApp
    }, function (err, obj) {
        if (err) {
            callback(err, null)
        }
        if (!obj) {
            obj = exports.addNewShare(userId, topicId, targetApp, feedsType)
        }
        exports.getSpecialTopic(topicId, function (err, topicObj) {
            if (err) {
                callback(err, null)
            }
            exports.getUser(userId, function (err, userObj) {
                if (err) {
                    callback(err, null)
                }
                console.log(topicObj.imageURL);
                callback(null, {obj: shareData(topicObj.title, topicObj.summary, topicObj.imageURL ? [{imageURL: topicObj.imageURL}] : [], obj, topicObj.dateLastModified ? topicObj.dateLastModified.getTime() : topicObj.dateCreated.getTime(), userId, topicObj)});

            })

        })


    })
};

exports.shareActivity = function (userId, targetApp, activityId, callback) {
    var feedsType = 'activity';
    exports.shareIsExisted({
        userId: userId,
        feedsType: feedsType,
        feedsId: activityId,
        shareTo: targetApp
    }, function (err, obj) {
        if (err) {
            callback(err, null)
        }
        if (!obj) {
            obj = exports.addNewShare(userId, activityId, targetApp, feedsType)
        }
        exports.getNeighbourActivity(activityId, function (err, actObj) {
            if (err) {
                callback(err, null)
            }
            exports.getUser(userId, function (err, userObj) {
                if (err) {

                }
                callback(null, {obj: shareData(actObj.title, actObj.desc.length > 200 ? actObj.desc.substring(0, 200) : actObj.desc, actObj.images, obj, actObj.dateLastModified ? actObj.dateLastModified.getTime() : actObj.dateCreated.getTime(), userId)});

            })

        })

    })
};

exports.shareQuestion = function (userId, targetApp, questionId, callback) {
    var feedsType = 'question';
    var questionType = {
        'question': '邻里求助',
        'share': '邻里分享',
        'recommendation': '通知推荐',
        'alert': '紧急提醒',
        'activity': '邻里活动',
        'secondhand': '二手闲置',
        'free': '免费赠送',
        'lostAndFound': '失物招领',
        'advertisement': '邻里广告',
        'discount': '优惠折扣'
    };
    exports.shareIsExisted({
        userId: userId,
        feedsType: feedsType,
        feedsId: questionId,
        shareTo: targetApp
    }, function (err, obj) {
        if (err) {
            callback(err, null)
        }
        if (!obj) {
            obj = exports.addNewShare(userId, questionId, targetApp, feedsType)
        }
        exports.getQuestion(questionId, function (err, qustObj) {
            if (err) {
                callback(err, null)
            }
            exports.getUser(userId, function (err, userObj) {
                if (err) {

                }

                logger.info(qustObj.desc.length);

                callback(null, {obj: shareData(qustObj.community.communityName + "的" + questionType[qustObj.category], qustObj.desc.length > 200 ? qustObj.desc.substring(0, 200) : qustObj.desc, qustObj.images, obj, qustObj.dateLastModified ? qustObj.dateLastModified.getTime() : qustObj.dateCreated.getTime(), userId)});

            })

        })

    })
};


exports.getSharedFeeds = function (shareId, userId, cparams, callback) {

    var format = '?imageView2/2/format/jpg';

    Users.findOne({_id: userId}, function (err, user) {
        var typeName = {
            qst: "question",
            act: "activity",
            top: "specialTopic",
            app: "app"

        };

        if (cparams.feedsType == 'null' || cparams.feedsType == '(null)' || cparams.feedsType == 'h5') {
            cparams.feedsType = "question";
        }

        exports.getShareById(shareId, function (err, obj) {
            if (shareId == '1') {
                obj = {
                    _id: shareId,
                    feedsType: cparams.feedsType,
                    feedsId: cparams.feedsId,
                    uuid: cparams.uuid,
                    userId: cparams.userId
                }
            }

            switch (obj.feedsType) {
                case typeName.qst:
                    exports.getQuestion(obj.feedsId, function (err, qstObj) {
                        if (err) {
                            callback(err, null);
                        }
                        exports.updateShareCount(obj, function (err, o) {
                            if (err) {
                                callback(err, null);
                            }
                            qstObj._doc['type'] = 1;
                            qstObj._doc['communityName'] = qstObj.community.communityName;
                            qstObj._doc['categoryName'] = '帖子';
                            qstObj._doc['titleDesc'] = '小区邻居发起的';
                            qstObj._doc['replyCount'] = qstObj.replies.length;
                            qstObj._doc['dateCreated'] = qstObj.dateCreated.getTime();
                            qstObj._doc.createdBy._doc.images = qstObj.createdBy.images[0].imageURL.indexOf('http') == 0 ? qstObj.createdBy.images[0].imageURL : imgHost + qstObj.createdBy.images[0].imageURL + format;

                            var replies = [];
                            if (qstObj.replies != null && qstObj.replies.length > 0) {
                                replies = qstObj.replies.slice(0, 10)
                            }
                            var data = [];
                            async.eachSeries(replies, function (temp, callbackInner) {

                                temp.images.forEach(function (pic) {
                                    pic.imageURL = imgHost + pic.imageURL + '?imageView2/1/h/200/w/200/q/75/format/jpg';
                                });

                                if (temp.replyDesc != null && temp.replyDesc.indexOf(atFlag) != -1) {
                                    replyAt.findOne({replyId: temp._id + ''}, function (err, at) {
                                        if (at != null && at.uList != null) {
                                            at.uList.forEach(function (user, i) {
                                                temp.replyDesc = temp.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + user.nickName + ' ')
                                            });
                                        }
                                        var a = {
                                            nickName: temp.repliedBy.nickName,
                                            images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : imgHost + temp.repliedBy.images[0].imageURL + format,
                                            replyDesc: temp.replyDesc,
                                            replyDate: temp.dateReplied.getTime(),
                                            replyImages: temp.images
                                        };
                                        data.push(a);
                                        callbackInner()
                                    }).populate('uList', '_id nickName');
                                } else if (temp.replyDesc != null && temp.replyDesc != '') {
                                    var a = {
                                        nickName: temp.repliedBy.nickName,
                                        images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : imgHost + temp.repliedBy.images[0].imageURL + format,
                                        replyDesc: temp.replyDesc,
                                        replyDate: temp.dateReplied.getTime(),
                                        replyImages: temp.images
                                    };
                                    data.push(a);
                                    callbackInner(err);
                                } else {
                                    callbackInner()
                                }
                            }, function (err) {
                                qstObj._doc['replies'] = data;

                                callback(null, {obj: qstObj, "host": imgHost, format: format});
                            });
                        });
                    });
                    break;
                case typeName.act:
                    exports.getNeighbourActivity(obj.feedsId, function (err, actObj) {
                        if (err) {
                            callback(err, null);
                        }
                        exports.updateShareCount(obj, function (err, o) {
                            if (err) {
                                callback(err, null);
                            }
                            actObj._doc['type'] = 2;
                            actObj._doc['communityName'] = actObj.community.communityName;
                            actObj._doc['categoryName'] = '邻里活动';
                            actObj._doc['titleDesc'] = '小区邻居发起的';

                            actObj._doc['dateCreated'] = actObj.dateCreated.getTime();
                            if (actObj.deadline != null)
                                actObj._doc.deadline = actObj._doc.deadline.getTime();
                            actObj._doc['replyCount'] = actObj.replies.length;
                            actObj._doc.createdBy._doc.images = actObj.createdBy.images[0].imageURL.indexOf('http') == 0 ? actObj.createdBy.images[0].imageURL : imgHost + actObj.createdBy.images[0].imageURL + format;

                            var replies = [];
                            if (actObj.replies != null && actObj.replies.length > 0) {
                                replies = actObj.replies.slice(0, 10)
                            }
                            var data = [];

                            async.eachSeries(replies, function (temp, callbackInner) {
                                if (temp.replyDesc != null && temp.replyDesc.indexOf(atFlag) != -1) {
                                    replyAt.findOne({replyId: temp._id + ''}, function (err, at) {
                                        if (at != null && at.uList != null) {
                                            at.uList.forEach(function (user, i) {
                                                temp.replyDesc = temp.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + user.nickName + ' ')
                                            });
                                        }
                                        var a = {
                                            nickName: temp.repliedBy.nickName,
                                            images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : imgHost + temp.repliedBy.images[0].imageURL + format,
                                            replyDesc: temp.replyDesc,
                                            replyDate: temp.dateReplied.getTime()
                                        };
                                        data.push(a);
                                        callbackInner()
                                    }).populate('uList', '_id nickName');
                                } else if (temp.replyDesc != null && temp.replyDesc != '') {
                                    var a = {
                                        nickName: temp.repliedBy.nickName,
                                        images: temp.repliedBy.images[0].imageURL.indexOf('http') == 0 ? temp.repliedBy.images[0].imageURL : imgHost + temp.repliedBy.images[0].imageURL + format,
                                        replyDesc: temp.replyDesc,
                                        replyDate: temp.dateReplied.getTime()
                                    };
                                    data.push(a);
                                    callbackInner(err);
                                } else {
                                    callbackInner()
                                }
                            }, function (err) {
                                actObj._doc['replies'] = data;

                                var number = 0;
                                actObj.partake.forEach(function (par) {
                                    number += par.number;
                                });

                                actObj._doc['number'] = number;
                                var array = actObj.partake.slice(0, 5);

                                actObj._doc['partakeNum'] = actObj.partake.length;
                                var partake = [];
                                array.forEach(function (temp) {

                                    if (temp.partakeType == 2) {
                                        temp._doc.user = {
                                            nickName: temp.name,
                                            images: [{imageURL: wechatImage}]
                                        }
                                    }
                                    var b = {
                                        _id: temp.user._id,
                                        nickName: temp.user.nickName,
                                        images: temp.user.images[0].imageURL.indexOf('http') == 0 ? temp.user.images[0].imageURL : imgHost + temp.user.images[0].imageURL + format,
                                        number: temp.number,
                                        date: temp.time.getTime()
                                    };
                                    partake.push(b);
                                });

                                actObj._doc['partake'] = partake;
                                callback(null, {obj: actObj, "host": imgHost, format: format});
                            });
                        });
                    });
                    break;
                case typeName.top:
                    exports.getSpecialTopic(obj.feedsId, function (err, topObj) {
                        if (err) {
                            callback(err, null);
                        }
                        exports.updateShareCount(obj, function (err, o) {
                            if (err) {
                                callback(err, null);
                            }
                            topObj._doc['type'] = 3;
                            topObj._doc['communityName'] = user.community.communityName;
                            topObj._doc['categoryName'] = '专题';
                            topObj._doc['titleDesc'] = '推荐的有趣';
                            topObj._doc['dateCreated'] = topObj.dateCreated.getTime();
                            callback(null, {obj: topObj, "host": imgHost, format: format});
                        });
                    });
                    break;
                case typeName.app:
                    exports.updateShareCount(obj, function (err, o) {
                        if (err) {
                            callback(err, null);
                        }
                        callback(null, {});
                    });
                    break;
            }

        })
    }).populate('community', 'communityName');
};

exports.getUser = function (userId, callback) {
    Users.findOne({_id: userId}, callback).populate("community", "_id communityName")
};


exports.saveInvitationCode = function (userObj, code, callback) {
    Users.update({_id: userObj._id}, {invitationCode: code}, callback);
};

exports.getAppUserShareService = function (userId, params, callback) {
    Users.findOne({_id: userId}, 'nickName images community invitationCode', function (err, user) {
        var temp = {
            nickName: user.nickName,
            images: user.images[0].imageURL.indexOf('http') == 0 ? user.images[0].imageURL : imgHost + user.images[0].imageURL + '?imageView2/2/format/jpg',
            communityName: user.community.communityName,
            invitationCode: user.invitationCode,
            communityId: user.community
        };
        callback(err, temp);

        Share.update({uuid: params.uuid, userId: userId}, {
            $inc: {numberOfClick: 1},
            dateLastModified: new Date(),
            feedsType: params.feedsType
        }, {upsert: true}, function (err, result) {
        })

    }).populate('community', 'communityName')
};

exports.addPartake = function (input, callback) {

    var partakeNum;

    async.series([
        function (callbackInner) {
            NeighbourActivity.findOne({
                _id: input.activityId,
                status: true,
                isValid: true
            }, function (err, result) {
                if (result == null) {
                    callbackInner(ErrorMessage.ACTIVITY_CLOSE, null);
                } else {
                    if (result.deadline != null && result.deadline.getTime() < new Date().getTime()) {
                        callbackInner(ErrorMessage.ACTIVITY_CLOSE, null);
                    } else {
                        partakeNum = result.partakeNum;
                        callbackInner();
                    }
                }
            })
        },
        function (callbackInner) {
            neighbourActivity.findOne({
                _id: input.activityId,
                isValid: true,
                'partake.phone': input.phone
            }, 'partake', function (err, result) {
                if (result == null) {
                    var temp = {
                        number: input.number,
                        phone: input.phone,

                        note: input.note
                    };
                    neighbourActivity.update({_id: input.activityId}, {
                        $push: {partake: temp}, partakeNum: partakeNum + 1
                    }, callbackInner)
                } else {

                    neighbourActivity.update({
                        _id: input.activityId,
                        'partake.user': user._id
                    }, {
                        'partake.$.number': input.number,
                        'partake.$.phone': input.phone,
                        'partake.$.note': input.note,
                        'partake.$.time': new Date()
                    }).exec(callbackInner);
                }
            });
        },
        function (callbackInner) {
            neighbourActivity.update({_id: input.activityId}, {dateLastModified: new Date()}, callbackInner)
        },
        function (callbackInner) {
            neighbourActivity.findOne({_id: input.activityId}, '_id title partakeNum createdBy', function (err, result) {

                callbackInner(null, partakeNum);

                if (result.createdBy != user._id) {
                    var temp = new SystemMessage();
                    temp.toUser = result.createdBy;
                    temp.content.questionDesc = '';
                    temp.content.replyDesc = '参加了您的活动' + '【' + result.title + '】';
                    temp.content.title = user.nickName;
                    temp.content.contentId = result._id;
                    temp.content.contentType = 'partake';
                    temp.content.questionCreatedBy = result.createdBy;
                    temp.category = 'partake';
                    temp.fromUser = user._id;
                    temp.save();

                    //个推
                    var content = {
                        type: 1,
                        flag: 1,
                        openType: 5,
                        contentId: result._id,
                        createdBy: result.createdBy,
                        desc: user.nickName + '参加了您的活动' + '【' + result.title + '】'
                    };
                    var pushData = {
                        uList: [result.createdBy],
                        content: content,
                        type: 'user'
                    };
                    toolUtil.putMessageGetuiPushMQ(pushData);
                }
            });
        }
    ], callback)

};

exports.getPartakesByActivityId = function (pageNo, activityId, callback) {

    var currentPage = 1;
    if (pageNo != '' && pageNo != null) {
        currentPage = pageNo;
    }
    var pageSize = 10;


    NeighbourActivity.findOne({_id: activityId}, "partake", function (err, result) {
        if (result != null && result.partake != null) {
            result.partake.sort(function (a, b) {
                return b.time - a.time;
            });
            currentPage = Number(currentPage);
            currentPage = currentPage - 1;
            result.partake = result.partake.slice(currentPage * pageSize, (currentPage + 1) * pageSize);
        }

        result.partake.forEach(function (par) {

            if (par.partakeType == 2) {
                par._doc.user = {
                    nickName: par.name,
                    images: [{imageURL: wechatImage}]
                }
            }

            if (par.user.images != null) {
                par.user.images.forEach(function (img) {
                    img.imageURL = img.imageURL.indexOf('http') != -1 ? img.imageURL : fastDfsHostIp + img.imageURL;
                })
            }
        });
        callback(err, result);
    }).populate('partake.user', 'nickName images');
};

exports.joinInActivityByWechatService = function (activityId, input, callback) {
    var partakeNum;
    async.series([
        function (callbackInner) {
            NeighbourActivity.findOne({
                _id: activityId,
                status: true,
                isValid: true
            }, function (err, result) {
                logger.info(result);
                if (result == null) {
                    callbackInner({message: '活动已结束'}, null);
                } else {
                    if (result.deadline != null && result.deadline.getTime() < new Date().getTime()) {
                        callbackInner({status: 3, message: '活动已结束'}, null);
                    } else {
                        partakeNum = result.partakeNum;
                        callbackInner();
                    }
                }
            })
        },
        function (callbackInner) {
            NeighbourActivity.findOne({
                _id: activityId,
                isValid: true,
                'partake.phone': input.phone
            }, 'partake', function (err, result) {
                if (result == null) {
                    NeighbourActivity.update({_id: activityId}, {
                        $push: {partake: input}, partakeNum: partakeNum + 1
                    }, callbackInner)
                } else {
                    callbackInner({status: 2, message: '已经参加过，不能再参加'}, null);
                }
            });
        },
        function (callbackInner) {
            NeighbourActivity.update({_id: activityId}, {dateLastModified: new Date()}, callbackInner)
        },
        function (callbackInner) {
            NeighbourActivity.findOne({_id: activityId}, '_id title partakeNum createdBy', function (err, result) {

                callbackInner(null, partakeNum);

                var temp = new SystemMessage();
                temp.toUser = result.createdBy;
                temp.content.questionDesc = '';
                temp.content.replyDesc = '参加了您的活动' + '【' + result.title + '】';
                temp.content.title = input.name;
                temp.content.contentId = result._id;
                temp.content.contentType = 'partake';
                temp.content.questionCreatedBy = result.createdBy;
                temp.category = 'partake';
                temp.save();

                //个推
                var content = {
                    type: 1,
                    flag: 1,
                    openType: 5,
                    contentId: result._id,
                    createdBy: result.createdBy,
                    desc: input.name + '参加了您的活动' + '【' + result.title + '】'
                };
                var pushData = {
                    uList: [result.createdBy],
                    content: content,
                    type: 'user'
                };
                toolUtil.putMessageGetuiPushMQ(pushData);
            });
        }
    ], callback)
};

exports.addQrcodeStatistic = function (input, callback) {
    var sql = "insert into qrcode_download_statistic values (null,'" + input.channel + "'," + new Date().getTime() + ")";
    logger.info(sql);
    mysqlUtil.query(sql, callback);
};

exports.addQrcodeStatistic = function (input, callback) {
    var sql = "insert into qrcode_download_statistic values (null,'" + input.channel + "'," + new Date().getTime() + ")";
    logger.info(sql);
    mysqlUtil.query(sql, callback);
};

exports.addInvitationShare = function (input, callback) {

    var phone = input.phone;

    Users.findOne({mobilePhone: phone}, function (err, user) {
        if (user != null) {
            callback(err, 2);
        } else {
            invitationShare.findOne({phone: phone}, function (err, result) {
                if (result != null) {
                    callback(err, 3);
                } else {
                    var invitation = new invitationShare();
                    invitation.inviter = input.userId;
                    invitation.invitationCode = input.code;
                    invitation.phone = input.phone;
                    invitation.type = 1;
                    invitation.save(callback(err, 1));
                }
            });
        }
    });

};

exports.getCommunityReward = function (input, callback) {

    //var communityId = input.communityId;
    //
    //var sql = "select * from voucher_type where id = (select voucher_type_id from voucher_reward_rule where community_id = '" + communityId + "' and reward_source = 1)"
    //mysqlUtil.query(sql, function (err, result) {
    //    if (result == null || result.length == 0) {
    //        callback(err, 0);
    //    } else {
    //        var reward = result[0];
    //        if (reward.type == 2) {
    //            callback(err, parseInt(reward.voucher_val / 10));
    //        } else {
    callback(null, REGISTER_SCORE);
    //}
    //    }
    //});

};

exports.getSharePageGoods = function (callback) {

    Goods.find({
        isValid: true
    }, 'title desc images presentPrice originalPrice dealStatus type community createdBy releaseDate location').skip(0).limit(4).sort('-dateCreated').exec(function (err, result) {
        Goods.count({
            isValid: true
        }, function (err, count) {
            result.forEach(function (temp) {
                if (temp.images != null && temp.images.length > 0) {
                    temp._doc.pic = imgHost + temp.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg'
                }
            });
            var data = {
                list: result,
                count: count
            };
            callback(err, data);
        });
    });
};

exports.getGoodsDetail = function (goodsId, callback) {
    var key = "goods:" + goodsId + ":detail";

    redisClient.hincrby(key, 'browner', 1);


    logger.info(goodsId);
    Goods.findOne({_id: goodsId}, 'title desc images presentPrice originalPrice dealStatus type community createdBy releaseDate location category')
        .populate('createdBy', 'nickName images huanxinUserName')
        .populate('community', 'communityName')
        .populate('category', '_id name')
        .exec(function (err, goods) {
            logger.info(goods);
            async.eachSeries(goods.images, function (temp, callbackInner) {
                temp.imageURL = imgHost + temp.imageURL + '?imageView2/1/h/300/w/300/q/75/format/jpg';
                callbackInner();
            }, function () {
                goods._doc.releaseDate = goods.releaseDate.getTime();
                var opt = [
                    key,
                    'browner',
                    'replyCount',
                    'collectionNum'
                ];
                if (goods.createdBy.images[0].imageURL.indexOf("http://") < 0) {
                    goods._doc.createdBy.images[0].imageURL = imgHost + goods.createdBy.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                }
                redisClient.hmget(opt, function (err, result) {
                    goods._doc.browner = result[0] == null ? 0 : result[0];
                    goods._doc.replyCount = result[1] == null ? 0 : result[1];
                    goods._doc.collectionNum = result[2] == null ? 0 : result[2];
                    callback(err, goods)
                });
            });
        });
};


exports.getCommunityActivity = function (activityId, input, callback) {
    communityActivity.findOne({_id: activityId}, function (err, activity) {
            var beginTime = activity.beginDate;
            var endDate = activity.endDate;

            activity.images.forEach(function (temp) {
                logger.info(temp.imageURL);
                temp.imageURL = imgHost + temp.imageURL + '?imageView2/1/h/276/w/750/q/75/format/jpg'
            });

            activity._doc.beginDate = beginTime.getFullYear() + "-" + (beginTime.getMonth() + 1) + "-" + beginTime.getDate();
            activity._doc.endDate = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate();
        }
    )
    ;
}
;

exports.getShareRestfulByCondition = function (input, callback) {

    var date = new Date();

    date.setMinutes(date.getMinutes() - 1);

    Share.find({userId: input.userId, dateCreated: {$gt: date}}, function (err, result) {

        if (result != null && result.length > 0) {
            callback(err, true);
        } else {
            callback(err, false);
        }

    });

};

exports.getShareContentByKey = function (input, callback) {

    var key = input.key;

    shareContent.findOne({key: key}).sort({dateCreated: -1}).exec(function (err, result) {
        if (result == null) return callback();

        if (result.image != null && result.images != '') {
            if (result.image.indexOf("http://") < 0) {
                result._doc.shareImg = imgHost + result.image + '?imageView2/1/w/200/h/200/q/75/format/jpg';
            } else {
                result._doc.shareImg = result.image;
            }
        }

        callback(err, result);
    });

};

exports.getTopic = function (input, callback) {
    topic.findOne({_id: input.topicId}, function (err, result) {
        topic.update({_id: input.topicId}, {$inc: {browserCount: 1}}).exec();
        if (result.images != null) {
            result._doc.topicImage = imgHost + result.images[0].imageURL + '?imageView2/1/w/200/h/200/q/85/format/jpg'
        }
        callback(err, result);
    });
}
;

exports.getShareByTopicId = function (input, callback) {
    var opt = {
        isValid: true
    };

    if (input.ts == 0) {
        //opt.dateCreated = {$gt: Number(input.ts)};
    } else {
        opt.dateCreated = {$lt: Number(input.ts)};
    }

    opt.topicId = input.topicId;
    //opt.community = user.community._id;
    if (input.around == 'around') {
        opt['$and'] = [{$or: [{community: user.community._id}, {aroundCommunity: user.community._id}]},
            {$or: [{category: 'share'}, {category: 'advertisement'}]}];
    } else {
        opt['$and'] = [{}, {$or: [{category: 'share'}, {category: 'advertisement'}]}];
        //opt['$or'] = [{category: 'share'}, {category: 'advertisement'}];
    }

    Question.find(opt, 'praiseCount _id desc categoryOrder community replies score ' +
        'category status images replies dateCreated createdBy')
        //.populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
        .populate('community', '_id communityName')
        .populate('createdBy', '_id nickName images authenticationStatus roomUnit showUnit userRole exp')
        .sort({dateCreated: -1}).limit(listPageSize).exec(function (err, results) {
            if (err) {
                callback(err, null)
            } else {
                async.each(results, function (temp, callbackInner) {

                        if (temp.createdBy.images != null && temp.createdBy.images.length > 0) {
                            if (temp.createdBy.images[0].imageURL.indexOf("http://") < 0) {
                                temp._doc.headImg = imgHost + temp.createdBy.images[0].imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                            } else {
                                temp._doc.headImg = temp.createdBy.images[0].imageURL;
                            }
                        }
                        if (temp.images != null) {
                            for (var i = 0; i < temp.images.length; i++) {
                                var tempImg = temp.images[i];
                                if (tempImg.imageURL.indexOf("http://") < 0) {
                                    tempImg.imageURL = imgHost + tempImg.imageURL + '?imageView2/1/w/200/h/200/q/75/format/jpg';
                                }
                            }
                        }
                        temp._doc.dateCreated = temp.dateCreated.getTime();
                        callbackInner()
                    },
                    function (err) {
                        var data = {};

                        //新帖子数量超过一页返回下一页时间戳
                        if (results.length >= listPageSize) {
                            data.nextTs = results[results.length - 1].dateCreated;
                        }

                        data.list = results;

                        callback(err, data);
                    }
                )
                ;
            }
        }
    )
    ;
}
;
